package cn.myjava.gupao.mode.singleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

/**
 * Created by RenFu
 * Date: 2019/5/12
 */
public class TestSingleton {

    public static void main(String[] args) {
        reflect();

        serialization();
    }

    /**
     * 通过反射破坏单例
     */
    public static void reflect() {
        try {
            // 通过反射测试破坏单例模式（懒汉式单例）
            Class<?> clazz = LazySimpleSingleton.class;
//            Class<?> clazz = LazyInnerClassSingleton.class;
//            Class<?> clazz = EnumSingleton.class;
            // 通过反射拿到私有的构造方法
            Constructor constructor = clazz.getDeclaredConstructor(null);
            // 强制访问，强吻，不愿意也要吻
            constructor.setAccessible(true);
            // 通过反射得到实例对象
            Object o1 = constructor.newInstance();
            Object o2 = constructor.newInstance();
            System.out.println(o1 == o2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过序列化破坏单例
     */
    public static void serialization() {
        SerializableSingleton s1 = null;
        SerializableSingleton s2 = SerializableSingleton.getInstance();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("SerializableSingleton.obj");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(s2);
            oos.flush();
            oos.close();

            FileInputStream fis = new FileInputStream("SerializableSingleton.obj");
            ObjectInputStream ois = new ObjectInputStream(fis);
            s1 = (SerializableSingleton)ois.readObject();
            ois.close();

            System.out.println(s1);
            System.out.println(s2);
            System.out.println(s1 == s2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
